using System;
using System.Collections.Generic;
using Loc.HibernateMini.IFaces;

namespace Loc.HibernateMini.Cache {
	public class SimpleCache : ICache
	{
        private Dictionary<string, IPersistent> _elements = new Dictionary<string, IPersistent>();
		
		public IPersistent Get(int id, Type type)
		{
			IPersistent value;
			_elements.TryGetValue(GetCacheId(id, type), out value);
			return value;
			
		}
		public void Put(IPersistent obj)
		{
            string key = GetCacheId(obj);
			if(!_elements.ContainsKey(key)){
				_elements.Add(key, obj);
			} else {
				_elements[key] = obj;
			}
		}

		public void Remove(IPersistent persistent)
		{
			_elements.Remove(GetCacheId(persistent));
		}

	    public void RemoveAll()
	    {
            _elements.Clear();
	    }


        private string GetCacheId(IPersistent pobj)
		{
			return GetCacheId(pobj.Id,pobj.GetType());
		}
		private string GetCacheId(int id,Type type) {
			if (id == 0) {
				throw new Exception("Can't put not saved object in cache");
			}
			return (type.ToString() + id.ToString());
		}
	}
	
}
